package org.zuel.innovative.power;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
@Log4j2
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    private TicketServer ticketServer;

    @Autowired
    private Hostholder hostHolder;

    @Autowired

    /**
     * 在 Controller 执行之前被调用
     * 检查凭证状态，若凭证有效则在本次请求中持有该用户信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,  Object handler) throws Exception {
        // 从 cookie 中获取凭证
        String ticket = request.getHeader("ticket");
        if (ticket != null) {
            // 查询凭证
            LoginTicket loginTicket = ticketServer.findLoginTicket(ticket);
            // 检查凭证状态（是否有效）以及是否过期
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                // 根据凭证查询用户
                User user = userService.selectByPrimeKey(loginTicket.getUserId());
                // 在本次请求中持有用户信息
                hostHolder.setUser(user);
            }
        }else{
            log.info("未识别出ticket...");
            log.info("addr:  "+request.getRemoteAddr());
        }
        return true;
    }

}
